package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(Employee employee, Long[] ids) {

        //密码加密 使用 用户名 作为 "盐"

        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName().toString());
        employee.setPassword(md5Hash.toString());

        employeeMapper.insert(employee);
        if (ids != null && ids.length > 0) {
            //处理中间表
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    @Override
    public List<Employee> selectAll() {
        List<Employee> employees = employeeMapper.selectAll();
        return employees;
    }

    @Override
    public void updateByPrimaryKey(Employee employee, Long[] ids) {
        //删除原本的关系
        employeeMapper.deleteRelation(employee.getId());
        if (ids != null && ids.length > 0) {
            //处理中间表
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
        employeeMapper.updateByPrimaryKey(employee);
    }

    @Override
    public PageInfo query(QueryObject qo) {
        //使用 分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        //调用startPage 方法后 ,会对下一句sql进行拦截,并进行改造成分页的 sql  千万注意哦
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<Employee>(employees);

    }

    @Override
    public Employee login(String username, String password) {
        if (!StringUtils.hasLength(username)) {
            throw new RuntimeException("用户名不能为空");
        }
        if (!StringUtils.hasLength(password)) {
            throw new RuntimeException("密码不能为空");
        }
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) {
            throw new RuntimeException("用户名与密码不匹配!");
        }
        return employee;
    }

    @Override
    public void updatePassword(String oldPassword, String newPassword) {
        //获取当前用户的员工
        Employee employee = UserContext.getCurrentUser();


        if ((oldPassword.equals(employee.getPassword())) || (!StringUtils.hasLength(oldPassword)) || (!StringUtils.hasLength(newPassword))) {
            throw new RuntimeException("原密码和新密码不匹配, 请重新输入!");
        } else {
            employeeMapper.updatePassword(employee.getId(), newPassword);
        }
    }


    //重置密码
    @Override
    public void resetPassword(String newPassword, Long id) {

        if (!StringUtils.hasLength(newPassword)) {
            throw new RuntimeException("请重新输入您即将要重置的密码!");
        }
        employeeMapper.resetPassword(newPassword, id);

    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }


    //用来验证 用户名的
    @Override
    public Employee selectByName(String name) {
        Employee employee = employeeMapper.selectByName(name);
        return employee;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {

        //把接受到文件以 excel 的 方式进行操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //从索引为1的行数开始读(忽略标题行)
        for (int i = 1; i <= lastRowNum; i++) {
            //获取行数据
            Row row = sheet.getRow(i);
            String name = row.getCell(0).getStringCellValue();
            //判断如果用户名为空 就不再读下去了
            if (!StringUtils.hasLength(name.trim())) {
                return;
            }
            Employee employee = new Employee();
            employee.setName(name);
            employee.setEmail(row.getCell(1).getStringCellValue());
            Cell cell = row.getCell(2);
            if (cell.getCellType().equals(CellType.STRING)) {
                employee.setAge(Integer.valueOf(cell.getStringCellValue()));
            }else {
                employee.setAge((int)cell.getNumericCellValue());
            }
            //转成 Integer类型
            Md5Hash md5Hash = new Md5Hash("1",employee.getName(),1);
            employee.setPassword(md5Hash.toString());
            this.insert(employee,null);
        }
    }


}
